﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Elsa.Services.Models;
using HengTong.Model;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TiaoTaoHelper.Wtm.Interfaces;
using TiaoTaoHelper.Wtm.Models;
using TiaoTaoHelper.Wtm.Workflow;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.WorkFlow;

namespace HengTong.ViewModel.Hr.SysHrStaffNeedRequestBillVms;

public partial class SysHrStaffNeedRequestBillVm
{
    // 用人需求申请流程结束后，把数据增加到用人需求池中
    [WorkflowOperation("添加到用人需求池", "将申请数据添加到用人需求池", "用人申请")]
    public async Task AddToNeedPool(ActivityExecutionContext context)
    {
        var scope = Wtm.ServiceProvider.CreateScope();
        var logger = scope.ServiceProvider.GetRequiredService<ILogger<SysHrStaffNeedRequestBillVm>>();

        string currentUser = "workflow";
        if (context.Input is WtmApproveInput input)
        {
            currentUser = input.CurrentUser?.ITCode ?? "workflow";
        }

        if (Entity == null || Entity.ID == Guid.Empty)
        {
            MSD.AddModelError(" ", "单据数据不存在");
            return;
        }

        // 查询当前用人需求申请子表
        var entries = await DC.Set<SysHrStaffNeedRequestBillEntry>()
            .Where(x => x.HrStaffNeedId == Entity.ID)
            .ToListAsync();

        // 批量生成唯一编号
        var billNumbers = await GenerateUniqueBillNumbers("YRC", entries.Count);

        for (int i = 0; i < entries.Count; i++)
        {
            var entry = entries[i];
            var pool = new SysHrStaffPool
            {
                StaffNeedEntryId = entry.ID,
                HrStatus = HrStatus.已审核,
                BillNo = billNumbers[i], // 使用预生成的唯一编号
                CreateBy = Entity.CreateBy ?? Wtm.LoginUserInfo?.ITCode,
                CreateTime = DateTime.Now
            };
            await DC.Set<SysHrStaffPool>().AddAsync(pool);
            logger.LogInformation("已将子表ID {EntryId} 添加到用人需求池，编号：{BillNo}", entry.ID, billNumbers[i]);
        }

        // 更新单据状态
        Entity.WorkflowStatus = WorkflowStatus.已完成;
        DC.UpdateProperty(Entity, x => x.WorkflowStatus);
        logger.LogInformation("单据编码 {BillCode} 状态更新为已完成", Entity.BillCode);

        await DC.SaveChangesAsync();
        logger.LogInformation("用人需求池插入完成，BillId: {BillId}", Entity.ID);
    }

    [WorkflowOperation("驳回", "将单据状态设置为草稿", "用人申请")]
    public async Task Reject(ActivityExecutionContext context)
    {
        Entity.BillStatus = BillStatus.草稿;
        if (Entity is IBasePoco poco)
        {
            poco.UpdateTime = DateTime.Now;
            DC.UpdateProperty(Entity, x => x.UpdateTime);
            if (context.Input is WtmApproveInput input)
            {
                poco.UpdateBy = input.CurrentUser?.ITCode ?? "workflow";
                DC.UpdateProperty(Entity, x => x.UpdateBy);
            }
        }

        DC.UpdateProperty(Entity, x => x.BillStatus);
        await DC.SaveChangesAsync();
    }

    [WorkflowOperation("取消", "将流程状态设置为取消", "用人申请")]
    public async Task Cancel(ActivityExecutionContext context)
    {
        if (Entity is IBasePoco poco)
        {
            poco.UpdateTime = DateTime.Now;
            DC.UpdateProperty(Entity, x => x.UpdateTime);
            if (context.Input is WtmApproveInput input)
            {
                poco.UpdateBy = input.CurrentUser?.ITCode ?? "workflow";
                DC.UpdateProperty(Entity, x => x.UpdateBy);
            }
        }

        if (Entity is IBill bill)
        {
            bill.WorkflowStatus = WorkflowStatus.已取消;
            DC.UpdateProperty(Entity, x => x.WorkflowStatus);
        }

        await DC.SaveChangesAsync();
    }


    // 批量生成唯一编号的方法
    private async Task<List<string>> GenerateUniqueBillNumbers(string prefix, int count)
    {
        var dateStr = DateTime.Now.ToString("yyyyMMdd");
        var result = new List<string>();

        // 查询当日最大流水号
        var maxBillNo = await DC.Set<SysHrStaffPool>()
            .Where(x => x.BillNo.StartsWith(prefix + dateStr))
            .Select(x => x.BillNo)
            .ToListAsync();

        var maxSequence = 0;
        if (maxBillNo.Any())
        {
            maxSequence = maxBillNo
                .Select(x => int.TryParse(x.Substring(x.Length - 3), out int seq) ? seq : 0)
                .DefaultIfEmpty(0)
                .Max();
        }

        // 批量生成连续编号
        for (int i = 1; i <= count; i++)
        {
            result.Add($"{prefix}{dateStr}{(maxSequence + i):D3}");
        }

        return result;
    }
}